// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

namespace Admin.NET.Core;

/// <summary>
/// 用户跨租户权限表
/// </summary>
[SugarTable(null, "用户跨租户权限表")]
[SysTable]
[SugarIndex("index_{table}_UT", nameof(UserId), OrderByType.Asc, nameof(TargetTenantId), OrderByType.Asc, IsUnique = true)]
[SugarIndex("index_{table}_U", nameof(UserId), OrderByType.Asc)]
public class SysUserCrossTenant : EntityBase
{
    /// <summary>
    /// 用户Id
    /// </summary>
    [SugarColumn(ColumnDescription = "用户Id")]
    [Required]
    public virtual long UserId { get; set; }

    /// <summary>
    /// 用户
    /// </summary>
    [Navigate(NavigateType.OneToOne, nameof(UserId))]
    public SysUser User { get; set; }

    /// <summary>
    /// 目标租户Id
    /// </summary>
    [SugarColumn(ColumnDescription = "目标租户Id")]
    [Required]
    public virtual long TargetTenantId { get; set; }

    /// <summary>
    /// 目标租户
    /// </summary>
    [Navigate(NavigateType.OneToOne, nameof(TargetTenantId))]
    public SysTenant TargetTenant { get; set; }

    /// <summary>
    /// 权限类型
    /// </summary>
    [SugarColumn(ColumnDescription = "权限类型")]
    [Required]
    public virtual CrossTenantPermissionEnum Permission { get; set; } = CrossTenantPermissionEnum.ReadOnly;

    /// <summary>
    /// 过期时间
    /// </summary>
    [SugarColumn(ColumnDescription = "过期时间", IsNullable = true)]
    public virtual DateTime? ExpireTime { get; set; }

    /// <summary>
    /// 是否激活
    /// </summary>
    [SugarColumn(ColumnDescription = "是否激活")]
    public virtual bool IsActive { get; set; } = true;

    /// <summary>
    /// 备注
    /// </summary>
    [SugarColumn(ColumnDescription = "备注", Length = 256, IsNullable = true)]
    [MaxLength(256)]
    public virtual string? Remark { get; set; }

    /// <summary>
    /// 权限授予者Id
    /// </summary>
    [SugarColumn(ColumnDescription = "权限授予者Id", IsNullable = true)]
    public virtual long? GrantedByUserId { get; set; }

    /// <summary>
    /// 权限授予者
    /// </summary>
    [Navigate(NavigateType.OneToOne, nameof(GrantedByUserId))]
    public SysUser GrantedByUser { get; set; }

    /// <summary>
    /// 验证权限是否有效
    /// </summary>
    /// <returns></returns>
    public bool IsValidPermission()
    {
        if (!IsActive) return false;
        if (ExpireTime.HasValue && ExpireTime.Value < DateTime.Now) return false;
        return true;
    }

    /// <summary>
    /// 验证是否有指定权限
    /// </summary>
    /// <param name="requiredPermission">所需权限</param>
    /// <returns></returns>
    public bool HasPermission(CrossTenantPermissionEnum requiredPermission)
    {
        if (!IsValidPermission()) return false;
        return Permission >= requiredPermission;
    }
}